/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui;

import controller.ProjetoDAO;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import models.Projeto;
import utils.nucleo.Nucleo;
import utils.observer.Observer;

/**
 *
 * @author Oliver Kraemer
 */
public class GridProjetos extends javax.swing.JPanel {

    private class GridProjetosObserver implements Observer {

        public GridProjetosObserver() {
            loadGrid();
        }
        
        @Override
        public void update() {
            loadGrid();
        }
    };

    private Projeto getProjetoSelecionado(){
        return (Projeto)jTListaProjetos.getModel().getValueAt( jTListaProjetos.getSelectedRow(), jTListaProjetos.getColumnCount()-1);
    }
    
    public GridProjetos() {
        initComponents();
        
        ProjetoDAO.getInstance().getSubject().registerObserver(new GridProjetosObserver());
    }

    protected void loadGrid() {
        DefaultTableModel modelo = (DefaultTableModel) jTListaProjetos.getModel();
        modelo.setRowCount(0);

        ArrayList<Projeto> projetos = ProjetoDAO.getProjetos();

        for (Projeto projeto : projetos) {
            modelo.addRow(new Object[]{
                projeto.getNome(),
                projeto.getSituacao(),
                projeto.getStatus(),
                formataData(projeto.getDataInicio()),
                formataData(projeto.getDataEntrega()),
                projeto.getCliente().getNome(),
                projeto
            });
        }
    }
    
    private String formataData(Date data) {
        if ( data == null ) {
            return "Não definida";
        }

        return new SimpleDateFormat("dd/MM/yyyy").format(data);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTListaProjetos = new javax.swing.JTable();
        Novo = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setToolTipText("Lista de Projetos");

        jTListaProjetos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Nome", "Situação", "Status", "Data Início", "Data Entrega", "Cliente", "null"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                true, true, true, true, true, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTListaProjetos.setToolTipText("");
        jTListaProjetos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTListaProjetos);
        jTListaProjetos.getColumnModel().getColumn(6).setMinWidth(0);
        jTListaProjetos.getColumnModel().getColumn(6).setPreferredWidth(0);
        jTListaProjetos.getColumnModel().getColumn(6).setMaxWidth(0);

        Novo.setText("Novo");
        Novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NovoActionPerformed(evt);
            }
        });

        jButton2.setText("Excluir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Alterar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton1.setText("Atividades");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton4.setText("Gráfico");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Novo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 281, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton1)
                    .addComponent(Novo)
                    .addComponent(jButton4))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void NovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NovoActionPerformed
        Nucleo.getInstance().getPrincipal().abrirTela(CadProjeto.class, false);
    }//GEN-LAST:event_NovoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (jTListaProjetos.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "Selecione um registro para Excluir.");
            return;
        }

        ProjetoDAO.excluir((Projeto) jTListaProjetos.getModel().getValueAt(jTListaProjetos.getSelectedRow(), jTListaProjetos.getColumnCount() - 1));

        JOptionPane.showMessageDialog(null, "Projeto excluído com sucesso.");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if (jTListaProjetos.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "Selecione um registro para Alterar.");
            return;
        }

        Nucleo.getInstance().getPrincipal().abrirTela(new CadProjeto(
                getProjetoSelecionado()),
                false
        );
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jTListaProjetos.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "Selecione um Projeto para definir as Atividades.");
            return;
        }
        
        Nucleo.getInstance().getPrincipal().abrirTela(
                new GridAtividades(getProjetoSelecionado())
        );
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        if (jTListaProjetos.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(null, "Selecione um Projeto para visualizar o Gráfico Burn-Down.");
            return;
        }
        
        Nucleo.getInstance().getPrincipal().abrirTela(
                new ViewBurnDown(getProjetoSelecionado())
        );
    }//GEN-LAST:event_jButton4ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Novo;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTListaProjetos;
    // End of variables declaration//GEN-END:variables
}